import {
	ref,watch
} from 'vue';
import {getToken} from "@/utils/token.js"
import {
	useWsStore
} from '@/stores/ws';
import * as S from "@/utils/storage.js"
export function useWs() {
	const wsStore = useWsStore()
	// 定义一个链接状态 用来判断ws是否链接的
	const connectFlag = ref(false)
	// 心跳检测 临时状态
	const heartTempFlag = ref(true)
	// 重连次数

	const repeatConnectNum = ref(10)
	// 发送消息的方法
	function sendSocketMessage(data) {
		uni.sendSocketMessage({
			data: JSON.stringify({token:getToken(),...data})
		});
	}

	function connect() {

		//  客户端 new WebSocket 的过程
		uni.connectSocket({
			url: 'ws://mianshi.9lele.com:3000'
		});
		//  onopen  创建链接成功 调用的方法
		uni.onSocketOpen(function(res) {
			// 设置链接状态
			connectFlag.value = true;
			wsStore.connectFlag = true
			// 向服务端发送一条 我上线了
			
			sendSocketMessage({type:'msg',data:"我上线了",token:getToken()})
			// 开启心跳检测 
			let heartInv = setInterval(() => {
				if (heartTempFlag.value) {
					heartTempFlag.value = false
					sendSocketMessage({type:'heart',data:"心跳检测"})
				} else {
					// 说明链接超时 或者断开，清空定时器
					clearInterval(heartInv)
					heartInv = null
					// 更改链接状态
					connectFlag.value = false
					// 进行重连操作
					wsStore.connectFlag = false
					repeatConnect()
				}

			}, 5000)

		});
		uni.onSocketMessage(function(res) {
			// 将收到的信息 转换成json
			let data = JSON.parse(res.data)
			if (data.type === 'heart') {
				// 此时代表心跳检测的 内容 
				heartTempFlag.value = true
			} else {
				// 不是心跳检测
				if(data.type==='memberMsg'){
					console.log(wsStore.chatList,66)
					wsStore.chatList.push({pos:'left',...data})
					console.log(wsStore.chatList)
				}else if(data.type==='msg'){
					let flag = 0
					try{
						flag =data.code?data.code:0
					}catch(e){
						flag=0
					}
					// 说明没登陆
					if(flag===1){
						S.remove("userInfo")
						uni.showToast({
							title:"请先登录！",
							duration:2000,
							success: () => {
								uni.closeSocket();
								uni.redirectTo({
									url:"/pages/login/login"
								})
							}
						})
					}else{
						// 把自己发送的消息 放到聊天记录里面
						// wsStore.chatList.push({pos:"right",...data})
					}
				}
			}

		});
	}

	// uni.connectSocket({
	//   url: 'wss://www.example.com/socket'
	// });

	async function repeatConnect() {
		// 第二次链接时间
		let tempNum = 5000
		// 循环 调用connect  定时调用connect
		if (wsStore.connectFlag) {
			// 说名此时链接着呢

		} else {
			// 说明链接断开 
			for (let i = 1; i <= repeatConnectNum.value; i++) {
				if (wsStore.connectFlag) {
					break;
				} else {
					connect()
					tempNum = tempNum * 2
					await wait(tempNum)
				}

			}

		}
	}

	function test() {
		setTimeout(() => {
			connectFlag.value = true
		}, 3000)
	}

	function wait(time = 1000) {
		return new Promise((res) => {
			setTimeout(() => {
				res(true)
			}, time)
		})

	}

	// 定时检测网络环境
	const wifFlag = ref(false)
	async function connectWs() {
		console.log(wsStore.connectFlag, 113)
		// 循环检测网络环境
		while (!wifFlag.value) {
			uni.getNetworkType({
				success: function(res) {
					console.log(res.networkType, 49);
					if (res.networkType != 'none') {
						wifFlag.value = true
						// 网络没问题 调用重连
						if (!wsStore.connectFlag) {
							repeatConnect()
						}

					}
				}
			});
			await wait(3000)
		}

	}

	watch(()=>wsStore.chatList.length,(newval)=>{
		console.log(newval,167,"聊天记录内容发生了变化")
		// 获取本地存储 
		let {username} = S.getItem("userInfo")
		if(newval){
			S.setItem("chatList_"+username,wsStore.chatList,1)
		}else{
			let temp = S.getItem("chatList_"+username)
			console.log(temp,173)
			if(temp){
				wsStore.chatList = temp
			}else{
				// wsStore.chatList =[]
			}
			
		}
	},{immediate:true})
	return {
		connectWs,
		sendSocketMessage
	};
}